package com.coder4j.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Service
public class FileStorageService {

    @Value("${app.upload.dir}")
    private String uploadDir;

    @Value("${app.server.url}")
    private String serverUrl;

    public String storeFile(MultipartFile file) {
        // 生成唯一的文件名
        String[] split = file.getOriginalFilename().split("\\\\");
        String fileName = UUID.randomUUID().toString() + "_" + split[split.length-1];
        Path filePath = Paths.get(uploadDir, fileName);
        try {
            // 创建目录（如果不存在）
            Files.createDirectories(filePath.getParent());

            // 存储文件
            Files.copy(file.getInputStream(), filePath);

            // 返回文件的URL
            return serverUrl + "/images/" + fileName;
        } catch (IOException e) {
            throw new RuntimeException("Failed to store file " + fileName, e);
        }
    }
}
